const Mock = require('mockjs')
const { find: findCouponDef, list: listCouponDef } = require('./coupon-def-items')
const { find: findOrgUnit } = require('./org-units')
const { find: findMovieLevel } = require('./movie-level')
const { getLoginUser } = require('./login')
const { list: listUser, findUserById } = require('./user')

let Coupons = []
const couponsPage = listCouponDef(1, 10)
let id = 1
for (let i = 0; i < couponsPage.data.records.length; ++i) {
  const userPage = listUser(1, 10, null, couponsPage.data.records[i].orgUnitId, null, null, null)
  for (let j = 1; j <= 3; ++j) {
    Coupons.push(Mock.mock({
      id: id++,
      name: couponsPage.data.records[i].name,
      type: couponsPage.data.records[i].type,
      userId: Mock.Random.integer(2, 18),
      amount: couponsPage.data.records[i].amount,
      initAmount: couponsPage.data.records[i].amount,
      orgUnitId: couponsPage.data.records[i].orgUnitId,
      movieLevelId: couponsPage.data.records[i].movieLevelId,
      maxAmount: couponsPage.data.records[i].maxAmount,
      couponDefinitionId: couponsPage.data.records[i].id,
      createUserId: userPage.data.records[j].id,
      start: Mock.Random.datetime(),
      end: Mock.Random.datetime(),
      status: Mock.Random.integer(0, 3),
      version: 1
    }))
  }
}

function grantCoupon(userId, item) {
  const r = JSON.parse(JSON.stringify(item))
  const u = getLoginUser()
  const couponDef = findCouponDef(item.couponDefinitionId)
  console.log('loginUser=' + JSON.stringify(u))
  r.createUserId = u.id
  r.id = Coupons[Coupons.length - 1].id + 1
  r.name = couponDef.name
  r.type = couponDef.type
  r.amount = couponDef.amount
  r.initAmount = couponDef.amount
  r.orgUnitId = couponDef.orgUnitId
  r.movieLevelId = couponDef.movieLevelId
  r.maxAmount = couponDef.maxAmount
  r.start = new Date()
  r.end = item.endTime ? item.endTime : (item.seconds < 0 ? new Date(new Date().getTime() - item.seconds * 24 * 3600 * 1000) : new Date(new Date().getTime() + item.seconds * 1000))
  r.status = 1
  r.version = 1
  r.userId = userId
  Coupons.push(r)
}

function saveCoupon(item) {
  const r = JSON.parse(JSON.stringify(item))
  const u = getLoginUser()
  const couponDef = findCouponDef(item.couponDefinitionId)
  console.log('loginUser=' + JSON.stringify(u))
  r.createUserId = u.id
  r.id = Coupons[Coupons.length - 1].id + 1
  r.name = couponDef.name
  r.type = couponDef.type
  r.amount = couponDef.amount
  r.initAmount = couponDef.amount
  r.orgUnitId = couponDef.orgUnitId
  r.movieLevelId = couponDef.movieLevelId
  r.maxAmount = couponDef.maxAmount
  r.start = new Date()
  r.end = item.endTime ? item.endTime : (item.seconds < 0 ? new Date(new Date().getTime() - item.seconds * 24 * 3600 * 1000) : new Date(new Date().getTime() + item.seconds * 1000))
  r.status = 0
  r.version = 1
  Coupons.push(r)
  return r.id
}

function list(page, limit, name, orgUnitId, type, timeType, start, end, userPhoneNumber) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  type = type ? parseInt(type) : null
  let mocks = Coupons.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    if (type && item.type !== type) return false
    return !(name && (!item.name || item.name.indexOf(name) === -1))
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  mocks = mocks.map(d => {
    const item = { ...d }
    const o = findOrgUnit(d.orgUnitId)
    if (o) {
      item.orgUnitName = o.name
    }
    const r = findMovieLevel(d.movieLevelId)
    if (r) {
      item.movieLevelName = r.name
    } else if (d.movieLevelId === -1) {
      item.movieLevelName = '无限制'
    } else {
      item.movieLevelName = '未知'
    }
    const u = findUserById(d.userId)
    if (u) {
      item.userNickname = u.nickname
      item.userPhoneNumber = u.phoneNumber
    }
    const cu = findUserById(d.createUserId)
    if (cu) {
      item.createUserNickname = cu.nickname
      item.createUserPhoneNumber = cu.phoneNumber
    }
    return item
  })
  const startTime = new Date(start)
  const endTime = new Date(end)
  mocks = mocks.filter(item => {
    if (timeType && item.start) {
      if (timeType === '1') {
        const comparison = new Date(item.start)
        if (comparison < startTime || comparison > endTime) {
          return false
        }
      }
    }
    if (userPhoneNumber && item.userPhoneNumber && item.userPhoneNumber.indexOf(userPhoneNumber) === -1) return false
    return true
  })
  return { success: true, data: { total: total, records: mocks }}
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < Coupons.length; ++i) {
    if (Coupons[i].id === id) {
      return Coupons[i]
    }
  }
  return null
}

function deleteRecord(id) {
  id = id ? parseInt(id) : null
  if (id) {
    Coupons = Coupons.filter(item => item.id !== id)
  }
}

module.exports = { list, grantCoupon, saveCoupon, find, deleteRecord }
